package com.rdc.qingkou.model;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;

import com.google.gson.Gson;
import com.rdc.qingkou.Application.MyApplication;
import com.rdc.qingkou.entity.Card;
import com.rdc.qingkou.entity.Result;
import com.rdc.qingkou.model.imodel.ISendCallBack;
import com.rdc.qingkou.retrofitService.ISendService;
import com.rdc.qingkou.utils.MyUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.rdc.qingkou.Application.MyApplication.getContext;
import static com.rdc.qingkou.Application.MyApplication.getsContentResolver;

public class SendModel {
    private static final String TAG = "SendModel";
    private Uri imageUri;
    private String imagePath;

    private ISendService ISend= MyUtils.getRetrofitProvider("").create(ISendService.class);

    public Uri  getImageUri() {
        File outputImage = new File(MyApplication.getAppCacheDir(), "output_image.JPEG");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();

        }

        if (Build.VERSION.SDK_INT >= 24) {

            imageUri = FileProvider.getUriForFile(MyApplication.getContext(), "com.rdc.qingkou.fileprovider", outputImage);
        } else {

            imageUri = Uri.fromFile(outputImage);
        }

        return imageUri;
    }

    @TargetApi(19)
    public String handleImageOnKitKat(Intent data){
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(getContext(),uri)){
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);

            }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                imagePath = getImagePath(contentUri,null);
            }

        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            imagePath = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            imagePath = uri.getPath();
        }

        return imagePath;


    }

    public String getImagePath(Uri uri,String selection){
        String path = null;
        Cursor cursor = getsContentResolver().query(uri,null,selection,null,null);
        if(cursor != null){
            if (cursor.moveToNext()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }cursor.close();
        }

        return path;

    }



    public void send(File mediaFile, File voiceFile, Card card, List<String> tag, final ISendCallBack callBack){

        MultipartBody.Part mediabody = null;
        MultipartBody.Part voicebody = null ;
        Gson tagGson = new Gson();

        if (mediaFile!=null){
           RequestBody MeidaFile =
                    RequestBody.create(MediaType.parse("multipart/form-data"), mediaFile);
            mediabody =
                   MultipartBody.Part.createFormData("media", mediaFile.getName(), MeidaFile);
        }else {
            mediabody = null;
        }
       if ( voiceFile!=null){
           RequestBody VoiceFile =
                   RequestBody.create(MediaType.parse("multipart/form-data"), voiceFile);
           voicebody =
                   MultipartBody.Part.createFormData("voice", voiceFile.getName(), VoiceFile);
       }else {
           voicebody = null;
       }


        ISend.send(mediabody,voicebody,card,tagGson.toJson(tag))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Result>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                          callBack.setDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull Result result) {
                        callBack.success();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        callBack.fail();

                    }

                    @Override
                    public void onComplete() {

                    }
                });




    }
}
